package com.tys.algorithm.bak.test;

//求数组最大值
public class Code18_GetMax {
    public static int getMax(int[] arr) {
        if (arr == null || arr.length == 0) {
            return 0;
        }
        return process(arr, 0, arr.length - 1);
    }

    public static int process(int[] arr, int L, int R) {
        if (L == R) {
            return arr[L];
        }
        int mid = L + ((R - L) >> 1);
        int leftMax = process(arr, L, mid);
        int rightMax = process(arr, mid + 1, R);
        return Math.max(leftMax, rightMax);
    }

    //生成随机数组
    public static int[] generaRandomArray(int maxLen, int maxValue) {
        int size = (int) (Math.random() * (maxLen + 1));
        int[] arr = new int[size];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int) (Math.random() * (maxValue + 1)) - (int) (Math.random() * (maxValue + 1));
        }
        return arr;
    }

    public static int testMax(int[] arr) {
        if (arr == null || arr.length == 0) {
            return 0;
        }
        int maxNum = arr[0];
        for (int num : arr) {
            if (num > maxNum) {
                maxNum = num;
            }
        }
        return maxNum;
    }

    public static void printArray(int[] arr) {
        if (arr == null) {
            return;
        }
        for (int num : arr) {
            System.out.print(num + ", ");
        }
        System.out.println();

    }

    public static void main(String[] args) {
        int maxLen = 100;
        int maxValue = 100;
        int testTimes = 10000;
        System.out.println("test begin");

//        int[] arr1 = {-56, -30, 29, 39};
//        System.out.println(getMax(arr1));
//        System.out.println(testMax(arr1));


        for (int i = 0; i < testTimes; i++) {
            int[] arr = generaRandomArray(maxLen, maxValue);
            if (getMax(arr) != testMax(arr)) {
                System.out.println(getMax(arr) + "!= " + testMax(arr));
                printArray(arr);
                System.out.println("Oops!");
                return;
            }
        }
        System.out.println("test end");
    }
}
